package com.zues.thread.create;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池
 *
 * @author zues
 * @date 12/7/2024 10:41 下午
 */
@Slf4j(topic = "c.ThreadPoolDemo")
public class ThreadPoolDemo {

    /**
     * ThreadPool七个参数：
     * int corePoolSize：常驻线程数量
     * int maximumPoolSize：线程池中最大支持多少线程数量
     * long keepAliveTime：超过常驻的线程存活时间
     * TimeUnit unit：存活时间单位
     * BlockingQueue<Runnable> workQueue：阻塞队列
     * ThreadFactory threadFactory：线程工厂，用于创建线程
     * RejectedExecutionHandler handler: 拒绝策略
     */
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            2,
            5,
            0, //存活时间会影响下面线程的执行次数
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(3),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.DiscardPolicy()
    );

    public void run() {
        try {
            for (int i = 1; i <= 15; i++) {
                log.info("运行了： {} 次", i);
                threadPool.execute(() -> {
                    log.info("{} 办理业务", Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
            log.error("error: {}", e.getMessage());
        } finally {
            //关闭线程池
            threadPool.shutdown();
        }
    }

}
